import React, { useState } from 'react';
import { connect } from "dva"
import { Flex, ActivityIndicator, Toast, Button, WingBlank, Carousel } from 'antd-mobile';
import Router from "umi/router";
import { tools } from "dcloud-utils"
import styles from './index.less';
import { httpUtil } from "dcloud-utils";
import { httpUrl } from "dcloud-core";

const timer = 10;

@connect(({ main }) => {
  return {
    token: main.get('token')
  }
})
export default class Home extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      carousel: [
          ''
      ],
      carouselHeight: 130,
      countDown: timer,
      count: '',
      btnDisable: false,
      btnText: '预约',
      wxReady: false
    }
  }

  

  /** 获取当日领取情况 */
  getMaxPurchaseLimit = (callback) => {
    const tenantId = localStorage.getItem("tenantId");
    httpUtil.get(httpUrl.maxPurchaseLimit, { tenantId: tenantId }).then((res) => {
      if (res.code === 200) {
        // 是否可预约
        if (res.data)
          callback()
        else
          Toast.fail(res.msg, 2);
      } else {
        Toast.fail(res.msg, 2);
      }
    }).catch(error => {
      Toast.fail('系统错误', 2);
    })
  }

  componentWillReceiveProps(newProps) {
    if(newProps.location.query.t)
      this.componentDidMount();
  }

  componentDidMount() {
    let banners = JSON.parse(localStorage.getItem("banners"));
        if (banners) {
          let carousel = [];
          banners.forEach((item) => {
            carousel.push(item.bannerUrl);
          })
          this.setState({
            carousel: carousel
          })
        }
  }

  /**
   * 卸载计时器
   */
  componentWillUnmount() {
    clearInterval(this.siv);
    this.setState({ btnText: '预约', btnDisable: false, countDown: timer })
  }

  onSubmit() {
    let { countDown } = this.state;
    if (!global.wx) {
      Toast.fail('获取微信授权失败，请稍后再试！', 2);
    }
    this.setState({ btnDisable: true })
    this.siv = setInterval(() => {
      this.setState({ countDown: (countDown--), btnText: '等待' + countDown, btnDisable: true }, () => {
        if (countDown === 0) {
          clearInterval(this.siv);
          this.setState({ btnText: '预约', btnDisable: false, countDown: timer })
        }
      });
    }, 1000);

    // 正式环境才开启定位
    if (process.env.LW_ENV == 'pro') {
      // 传入罗甸县adcode
      tools.getLocation(() => {
        this.getMaxPurchaseLimit(() => {
          Router.push('/submit')
        })
      })
    } else if (process.env.LW_ENV == 'test') {
      tools.getLocation(() => {
        this.getMaxPurchaseLimit(() => {
          Router.push('/submit');
        })
      })
    } else {
      Router.push('/submit');
    }
  }

  getCarousel() {
    return <div className={styles.carousel}>
      {
        this.state.carousel.length > 1 ? <Carousel
          autoplay={true}
          autoplayInterval={5000}
          infinite
        >
          {
            this.state.carousel.map((item, i) => {
              return <a key={i} style={{ height: this.state.carouselHeight }}>
                <img
                  src={item}
                  onError={(e) => {
                    e.target.onerror = null;
                    e.target.src = require('../../assets/images/banner.jpg')
                  }}
                  alt=""
                  onLoad={e => {
                    if (i === 0) {
                      this.setState({
                        carouselHeight: e.target.height
                      })
                    }
                  }}
                  style={{ verticalAlign: 'top' }}
                />
              </a>
            })
          }
        </Carousel> : <img onError={(e) => {
          e.target.onerror = null;
          e.target.src = require('../../assets/images/banner.jpg')
        }} src={this.state.carousel[0]? this.state.carousel[0] : require('../../assets/images/banner.jpg') } className={styles.onlyImg}></img>
      }
    </div>
  }

  render() {
    if (this.props.loading) {
      return <ActivityIndicator />
    }

    return (
      <div style={{ background: '#fff', marginBottom: '2rem' }}>
        <WingBlank>
          {this.getCarousel()}
          <Flex justify="between" style={{ boxShadow: "0px 4px 24px 0px rgba(0,0,0,0.08)", borderRadius: '0.5rem' }}>
            <Flex.Item>
              <img src={require('../../assets/images/kouzhao.jpg')} style={{ height: '6rem', maxWidth: '100%' }}></img>
            </Flex.Item>
            {/* <Flex.Item>
                    <Flex.Item>
                        <h4 style={{margin:0}}>防御口罩</h4>
                        <p>{this.state.count}人预约</p>
                    </Flex.Item>
                </Flex.Item> */}
            <Flex.Item>
              <Button disabled={this.state.btnDisable} onClick={this.onSubmit.bind(this)} style={{ width: '80%', height: '2rem', lineHeight: '2rem', color: 'white', borderRadius: '1rem', background: 'linear-gradient(135deg,rgba(108,202,255,1) 0%,rgba(74,113,255,1) 100%)' }}>{this.state.btnText}</Button>
            </Flex.Item>
          </Flex>
          <div style={{ background: '#fff', boxShadow: "0px 4px 24px 0px rgba(0,0,0,0.08)", marginTop: '1rem', borderRadius: '0.5rem', minHeight: '10rem', boxSizing: 'border-box', padding: '1rem' }}>
            <pre style={{ whiteSpace: 'pre-wrap', wordWrap: 'break-word' }}>{localStorage.getItem("rule") ? localStorage.getItem("rule") : ''}</pre>
          </div>
        </WingBlank>
      </div>
    )

  }
}